package com.jsnkj.basic.activity

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import com.bumptech.glide.Glide
import com.jsnkj.basic.AdLibApplication.Companion.getInstance
import com.jsnkj.basic.LibraryConfig
import com.jsnkj.basic.LibraryConfig.WX_APP_ID
import com.jsnkj.basic.R
import com.jsnkj.basic.adapter.WithDrawMoneyAdapter
import com.jsnkj.basic.advertisement.AdvertisementManager
import com.jsnkj.basic.bean.UserDataEntity
import com.jsnkj.basic.bean.UserLoginEntity
import com.jsnkj.basic.bean.WithdrawalsEntity
import com.jsnkj.basic.config.SpConfig
import com.jsnkj.basic.databinding.ActivityWithdrawBinding
import com.jsnkj.basic.dialog.BindPayDialog
import com.jsnkj.basic.mvvm.BaseKtActivity
import com.jsnkj.basic.util.ErrorResultUtil
import com.jsnkj.basic.util.SharePreferencesUtil
import com.tencent.mm.opensdk.constants.ConstantsAPI


/**
 * 提现界面
 */
class WithdrawActivity : BaseKtActivity<ActivityWithdrawBinding, WithDrawViewModel>(),
    View.OnClickListener {
    override val layoutId: Int
        get() = R.layout.activity_withdraw

    var itemAdapter: WithDrawMoneyAdapter? = null

    var bindPayDialog: BindPayDialog? = null


    var money = 0.0F

    var aliLoginIdStr: String = ""
    var realNameStr: String = ""
    var userEntity: UserDataEntity? = null


    override fun initView(savedInstanceState: Bundle?) {

        mVDB.clickListener = this

        mVDB.topTitle.txtTopTitle.text = "我要提现"
        mVDB.topTitle.imageReturn.setOnClickListener {
            onBackPressed()
        }

        mVDB.topTitle.ivTopRight1.visibility = View.VISIBLE
        Glide.with(this@WithdrawActivity).load(R.drawable.icon_withdraw_top)
            .into(mVDB.topTitle.ivTopRight1)

        mVDB.topTitle.ivTopRight1.setOnClickListener {
            ReceiptsDetailActivity.goToReceiptsDetail(this@WithdrawActivity, 1)
        }

        initData()

        userEntity = SharePreferencesUtil.getInstance().getUserBean()
        userEntity?.let { userEntity ->
            userEntity.user?.let { user ->
                initUser(user)
            }
        }

        AdvertisementManager.showLoadInteraction(this@WithdrawActivity, SpConfig.AD_TIME)
    }

    fun initUser(user: UserLoginEntity) {
        money = user.withdrawable_coins.toFloat() / SpConfig.goldCoinConversion

        mVDB.txtMoney.text = "${String.format("%.2f", money)}元"

        if (LibraryConfig.isEnablePayType()) {
            Glide.with(this@WithdrawActivity).load(R.mipmap.icon_wx_logo)
                .into(mVDB.ivNumberIcon)
            mVDB.tvWhitdrawUserName.text = "提现账号： ${user.showName()}"

            mVDB.tvBindAlipay.visibility = View.GONE
        } else {
            mVDB.tvBindAlipay.visibility = View.VISIBLE

            Glide.with(this@WithdrawActivity).load(R.drawable.icon_ali_zhifu_logo)
                .into(mVDB.ivNumberIcon)

            if (user.ali_login_id.isNullOrEmpty()) {
                mVDB.tvWhitdrawUserName.text = "未支付宝账号"
            } else {
                mVDB.tvWhitdrawUserName.text = "提现账号： ${user.real_name}"
            }


        }
    }

    private fun initData() {
        mVM.moneyListResult.observe(this) {
            initMoneyRecyclerView()
        }


        mVM.postApplyResult.observe(this) {
            com.jsnkj.basic.util.ToastUtils.show(it)
            onBackPressed()
        }

        mVM.postBindPayResult.observe(this) {
            dismissDialog()
            com.jsnkj.basic.util.ToastUtils.show(it)

            userEntity?.let { userEntity ->
                userEntity.user?.let { user ->
                    user.ali_login_id = aliLoginIdStr
                    user.real_name = realNameStr

                    initUser(user)
                }
                SharePreferencesUtil.getInstance().putUserBean(userEntity)
                com.jsnkj.basic.util.LogUtils.e("保存数据：" + SharePreferencesUtil.getInstance().getUserBean())
            }
        }


        mVM.errorResult.observe(this) {
            dismissDialog()
            ErrorResultUtil.errorResultToast(this@WithdrawActivity, it)
        }


        mVM.postMoneyList()

    }

    /**
     * 汇付八方提现
     */
    private fun huifubafangWithdraw(bean: WithdrawalsEntity){
        val deviceId = Settings.Secure.getString(this@WithdrawActivity.contentResolver, Settings.Secure.ANDROID_ID)
        val deviceType = Build.MODEL
        //1.调汇付八方授权接口
        mVM.getHuifubafangWithdrawOauth(object :
            com.jsnkj.basic.adlistener.HuifuOauthListener {
            override fun onOauthSuccess(huifuOauthRepsBean: com.jsnkj.basic.bean.HuifuOauthRepsBean?) {
                if("0".equals(huifuOauthRepsBean?.is_auth)){
                    //拉取微信小程序的认证
                    com.jsnkj.basic.wxapi.WechatHelper.getInstance(getInstance(), WX_APP_ID).launchMiniProgram(huifuOauthRepsBean?.gh_id,huifuOauthRepsBean?.path,
                        object :
                            com.jsnkj.basic.wxapi.PayResultListener {
                            override fun onPayResult(isSuccess: Boolean, message: String?) {
                                if(isSuccess){
                                    mVM.postWithdrawalApply(bean.id!!,deviceId,deviceType)
                                }else{
                                    com.jsnkj.basic.util.ToastUtils.show("汇付授权失败："+message);
                                }
                            }

                            override fun onPayCancel() {
                               com.jsnkj.basic.util.ToastUtils.show("汇付授权已取消");
                            }

                        })
                }else{
                    mVM.postWithdrawalApply(bean.id!!,deviceId,deviceType)
                }
            }

        });

    }

    private fun initMoneyRecyclerView() {

        if (null == itemAdapter) {
            itemAdapter = WithDrawMoneyAdapter(
                this@WithdrawActivity,
                mVM.moneyList,
                object : WithDrawMoneyAdapter.onItemClickListener {
                    override fun onItemCallBack(itemPosition: Int) {
                        for ((index, _) in mVM.moneyList.withIndex()) {
                            if (mVM.moneyList[index].isSelect) {
                                mVM.moneyList[index].isSelect = false
                            }
                        }
                        mVM.moneyList[itemPosition].isSelect = true
                        itemAdapter?.notifyDataSetChanged()
                    }
                })

            mVDB.rvMoney.apply {
                layoutManager = GridLayoutManager(this@WithdrawActivity, 3)
                adapter = itemAdapter
                visibility = View.VISIBLE
            }
        } else {
            itemAdapter?.notifyDataSetChanged()
        }
    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.tv_bind_alipay -> {
                if (null != bindPayDialog && bindPayDialog!!.isShowing) {
                    bindPayDialog?.dismiss()
                }

                bindPayDialog = BindPayDialog(this@WithdrawActivity,
                    object : BindPayDialog.onItemClickListener {
                        override fun itemClickResult(aliLoginId: String, realName: String) {
                            showDialog()
                            aliLoginIdStr = aliLoginId
                            realNameStr = realName

                            mVM.postWithdrawalApply(aliLoginId, realName)
                        }
                    })
                bindPayDialog?.show()
            }

            R.id.txt_withdrawal_balance -> {
                for ((_, bean) in mVM.moneyList.withIndex()) {
                    if (bean.isSelect) {
                        if (bean.value!!.toFloat() <= money) {
                           this.huifubafangWithdraw(bean);
                        } else {
                            com.jsnkj.basic.util.ToastUtils.show("您的余额不足")
                        }
                    }
                }
            }

        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == ConstantsAPI.COMMAND_LAUNCH_WX_MINIPROGRAM && resultCode == RESULT_OK) {
            if (data != null) {
                val extraData = data.getStringExtra("extraData")
                // 处理 extraData
            }
        }
    }


}